import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.Random;
import javax.mail.*;
import javax.mail.internet.*;

public class CustomerLoginFrame extends JFrame {
    private JTextField usernameField;
    private JPasswordField passwordField;
    private int failedAttempts = 0; // 记录失败登录尝试次数

    public CustomerLoginFrame() {
        setLocationRelativeTo(null);
        setTitle("客户登录");
        setSize(320, 250);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);

        JPanel panel = new JPanel();
        add(panel);

        JLabel userLabel = new JLabel("用户名:");
        panel.add(userLabel);

        usernameField = new JTextField(20);
        panel.add(usernameField);

        JLabel passwordLabel = new JLabel("密码:");
        panel.add(passwordLabel);

        passwordField = new JPasswordField(20);
        panel.add(passwordField);

        JButton customerLoginButton = new JButton("客户登录");
        panel.add(customerLoginButton);

        JButton forgotPasswordButton = new JButton("忘记密码");
        panel.add(forgotPasswordButton);

        JButton backButton =new JButton("返回登录界面");
        panel.add(backButton);

        backButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                dispose();
                LoginFrame loginFrame = new LoginFrame();
                loginFrame.setVisible(true);
            }
        });

        customerLoginButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                if (validateCustomerLogin(usernameField.getText(), new String(passwordField.getPassword()))) {
                    failedAttempts = 0; // 登录成功，重置失败次数
                    CustomerMenuFrame menuFrame = new CustomerMenuFrame();
                    menuFrame.setVisible(true);
                    dispose();
                } else {
                    failedAttempts++;
                    if (failedAttempts >= 5) {
                        lockAccount(usernameField.getText()); // 锁定账户
                    }
                    JOptionPane.showMessageDialog(CustomerLoginFrame.this, "登录失败，请检查用户名和密码。", "登录失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });

        forgotPasswordButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                String username = JOptionPane.showInputDialog("请输入用户名:");
                String email = JOptionPane.showInputDialog("请输入注册邮箱地址:");
                if (resetPassword(username, email)) {
                    JOptionPane.showMessageDialog(CustomerLoginFrame.this, "密码重置成功，请检查您的邮箱。", "重置成功", JOptionPane.INFORMATION_MESSAGE);
                    dispose();
                    LoginFrame loginFrame = new LoginFrame();
                    loginFrame.setVisible(true);
                } else {
                    JOptionPane.showMessageDialog(CustomerLoginFrame.this, "密码重置失败，请检查用户名和邮箱地址。", "重置失败", JOptionPane.ERROR_MESSAGE);
                }
            }
        });
    }

    // 验证客户登录的方法
    private boolean validateCustomerLogin(String username, String password) {
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM customers WHERE username = ? AND password = ? AND locked = false")) {
            preparedStatement.setString(1, username);
            preparedStatement.setString(2, password);
            ResultSet resultSet = preparedStatement.executeQuery();
            return resultSet.next(); // 如果有匹配的记录，则验证通过
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 重置密码的方法
    private boolean resetPassword(String username, String email) {
        String newPassword = generateRandomPassword();
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("UPDATE customers SET password = ? WHERE username = ? AND email = ?")) {
            preparedStatement.setString(1, newPassword);
            preparedStatement.setString(2, username);
            preparedStatement.setString(3, email);
            int affectedRows = preparedStatement.executeUpdate();

            if (affectedRows > 0) {
                sendEmail(email, newPassword);
                return true;
            }
            return false;
        } catch (SQLException e) {
            e.printStackTrace();
            return false;
        }
    }

    // 生成随机密码的方法
    private String generateRandomPassword() {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*()";
        Random random = new Random();
        StringBuilder password = new StringBuilder();
        for (int i = 0; i < 12; i++) {
            password.append(chars.charAt(random.nextInt(chars.length())));
        }
        return password.toString();
    }

    // 发送邮件的方法
    private void sendEmail(String to, String newPassword) {
        final String from = "your-email@example.com"; // 发送者邮箱地址
        final String host = "smtp.example.com"; // SMTP服务器地址
        final String username = "your-email@example.com"; // SMTP用户名
        final String password = "your-email-password"; // SMTP密码

        Properties properties = System.getProperties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.auth", "true");

        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
        });

        try {
            MimeMessage message = new MimeMessage(session);
            message.setFrom(new InternetAddress(from));
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));
            message.setSubject("密码重置通知");
            message.setText("您的新密码是: " + newPassword);

            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
    }

    // 锁定账户的方法
    private void lockAccount(String username) {
        try (Connection connection = DBUtil.getConnection();
             PreparedStatement preparedStatement = connection.prepareStatement("UPDATE customers SET locked = true WHERE username = ?")) {
            preparedStatement.setString(1, username);
            preparedStatement.executeUpdate();
            JOptionPane.showMessageDialog(this, "您的账户已被锁定，请联系管理员。", "账户锁定", JOptionPane.WARNING_MESSAGE);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
